package Thefourthdexperiment;

/**
 * Created by hasee on 2017/11/20.
 */
public class Linkedlist {private ListNode firstNode;     //定義鏈錶的 頭節點
    private ListNode lastNode;     // 。。。。。 為節點
    private String name;
    Linkedlist(String s)                            // 覆寫默認的構造器
    {
        name = s;
        firstNode = lastNode = null;    // 初始化成員變量
    }
    public Linkedlist()
    {
        this(" 鏈錶");
    }

    public void insertAtFront(Object insertItem)
    {
        if(isEmpty())
            firstNode = lastNode = new ListNode(insertItem);
        else
            firstNode = new ListNode(insertItem, firstNode);
    }

    public void insertAtBack(Object insertItem)
    {
        if(isEmpty())
            firstNode = lastNode = new ListNode(insertItem);
        else
            lastNode = lastNode.next = new ListNode(insertItem);
    }

    public Object removeFromFront()
    {
        Object removeItem = null;

        if(isEmpty())
            System.out.println("這個" + name + "是空的。");
        removeItem = firstNode.data;
        if(firstNode.equals(lastNode))
            firstNode = lastNode = null;
        else
            firstNode = firstNode.next;
        return removeItem;
    }

    public Object removeFromBack()
    {
        Object removeItem =null;
        if(isEmpty())
            System.out.println("這個 " + name + " 是空的。");
        removeItem = lastNode.data;
        if(firstNode.equals(lastNode))
            firstNode = lastNode = null;
        else
        {
            ListNode current = firstNode;
            while (current.next != lastNode)
                current = current.next;
            lastNode = current;
            current.next = null;
        }
        return removeItem;
    }

    public boolean isEmpty()
    {
        return firstNode ==  null;
    }

    public void print()
    {
        if(isEmpty())
        {
            System.out.println(" 空的 " + name);
            return;
        }
        System.out.print("這個 " + name + " 為 ： ");
        ListNode current = firstNode;

        while(current != null)
        {
            System.out.print(current.data.toString() + " ");
            current = current.next;
        }
        System.out.println("\n");
    }
}
